<template>
  <el-cascader v-if="!isEdit" class="wp100" @change="onChange" :options="options" :props="props" v-model="areaArry" :clearable="clearable" :placeholder="placeholder"></el-cascader>
</template>

<script>
import regionApi from '@/api/src/region'

export default {
  components: {},
  props: {
    value: {
      type: [Object, Array],
      default: () => {
        return {}
      }
    },
    clearable: {
      type: Boolean,
      default: true
    },
    showLevel: {
      type: Number,
      default: 2,
      validator (value) {
        return [1, 2, 3].includes(value)
      }
    },
    reload: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请选择所在地区'
    },
    checkStrictly: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      areaArry: [],
      provinceList: [],
      cityList: [],
      areaList: [],
      isEdit: true,
      props: {
        value: 'concatId',
        label: 'regionName',
        children: 'children',
        checkStrictly: false,
        multiple: false,
        lazy: true,
        lazyLoad (node, resolve) {
          let nodes = []
          if (node && node.data && node.data.id) {
            setTimeout(() => {
              if (node.level !== 3) {
                const params = {
                  level: node.level + 1,
                  pId: node.data.id,
                  maxRegionLevel: +node.data.showLevel - (node.data.id === '457' ? 1 : 0)
                }
                regionApi.getTreeChildren(params).then(_res => {
                  nodes = _res.map((item, index) => {
                    return {
                      index,
                      ...item,
                      showLevel: node.data.showLevel,
                      concatId: `${item.id}-${item.regionName}-${index}`,
                      leaf: !item.children
                    }
                  })
                  resolve(node.children && node.children.length ? [] : nodes)
                }).catch(() => {
                  resolve([])
                })
              }
            }, 0)
          }
        }
      },
      options: [],
      provinceSelected: {},
      citySelected: {},
      areaSelected: {}
    }
  },
  computed: {
    cloneValue: {
      get () {
        return this.value
      },
      set (value) {
        console.log('province:' + value)
      }
    }
  },
  watch: {
    cloneValue: {
      handler (value) {
        if (!value.provinceId) {
          this.areaArry = []
          this.isEdit = false
        }
      },
      immediate: true,
      deep: true
    },
    async reload (val) {
      if (val) {
        await this.getProvinceList()
        if (this.value.provinceId) {
          this.backArea(this.value)
        }
        this.$emit('finish-reload')
      }
    }
  },
  created () {
    this.props.checkStrictly = this.checkStrictly
  },
  async mounted () {
    await this.getProvinceList()
    if (this.cloneValue.provinceId) {
      this.backArea(this.cloneValue)
    }
  },
  methods: {
    handlerProvinceChange (orgCode) {
      this.getCityList(orgCode)
    },
    async getList (regionLevel = 1, pId) {
      const res = await regionApi.getTreeChildren({ regionLevel, pId, maxRegionLevel: +this.showLevel - (pId === '457' ? 1 : 0) })
      return res
    },
    // 省市区回填
    async backArea (val) {
      const isEmptyObject = !!Object.keys(val).length
      if (typeof val === 'object' && isEmptyObject) {
        let provinceIndex, cityIndex, areaIndex
        if (val.provinceId) {
          await this.getCityList(val.provinceId)
          provinceIndex = this.provinceList.findIndex(item => {
            return +item.id === +val.provinceId
          })
          this.options[provinceIndex].children = this.cityList
          this.provinceSelected = [
            val['provinceId'],
            val['provinceName'] || this.provinceList[provinceIndex].regionName,
            provinceIndex
          ]
          this.areaArry.splice(0, 1, this.provinceSelected.join('-'))
        }
        if (val.cityId) {
          await this.getAreaList(val.cityId)
          cityIndex = this.cityList.findIndex(item => {
            return +item.id === +val.cityId
          })
          this.options[provinceIndex].children[cityIndex].children = this.areaList
          this.citySelected = [
            val['cityId'] === 0 ? '' : val['cityId'],
            val['cityName'] || this.cityList[cityIndex].regionName,
            cityIndex
          ]
          this.areaArry.splice(1, 1, this.citySelected.join('-'))
        }
        if (val.countyId) {
          areaIndex = this.areaList.findIndex(item => {
            return +item.id === +val.countyId
          })
          this.areaSelected = [
            val['countyId'] === 0 ? '' : val['countyId'],
            val['countyName'] || this.areaList[areaIndex].regionName,
            areaIndex
          ]
          this.areaArry.splice(2, 1, this.areaSelected.join('-'))
        }
        this.isEdit = false
      }
    },
    async onChange (val) {
      await this.setSelected(val)
      const data = {
        provinceId: this.provinceSelected[0] || '',
        provinceName: this.provinceSelected[1] || '',
        cityId: this.citySelected[0] || '',
        cityName: this.citySelected[1] || '',
        countyId: this.areaSelected[0] || '',
        countyName: this.areaSelected[1] || ''
      }
      this.$emit('input', data)
      this.$emit('change', data)
    },
    async setSelected (val) {
      this.provinceSelected = (val[0] && val[0].split('-')) || []
      this.citySelected = (val[1] && val[1].split('-')) || []
      this.areaSelected = (val[2] && val[2].split('-')) || []
      if (val[0] && this.showLevel >= 2) {
        if (!val[1]) {
          await this.getCityList(this.provinceSelected[0])
        }
      }
      if (val[1] && this.showLevel === 3) {
        if (!val[2]) {
          await this.getAreaList(this.citySelected[0])
        }
      }
    },
    async getProvinceList () {
      const res = await this.getList(1, '-1')
      this.provinceList = this.mapItem(res)
      const _opt = JSON.stringify(this.provinceList)
      this.options = JSON.parse(_opt)
    },
    async getCityList (provinceId) {
      const res = await this.getList(2, provinceId)
      this.cityList = this.mapItem(res, false)
    },
    async getAreaList (cityId) {
      const res = await this.getList(3, cityId)
      this.areaList = this.mapItem(res, false)
    },
    mapItem (res, addChildren = true) {
      return res.map((item, index) => {
        return {
          index,
          ...item,
          showLevel: this.showLevel,
          concatId: `${item.id}-${item.regionName}-${index}`,
          leaf: !item.children
        }
      })
    }
  }
}
</script>

<style>
</style>
